<?php
// Copyright 2019 Hackware SpA <human@hackware.cl>
// Part of "Hackware Web Services Core", released under the MIT License terms.

namespace Hawese\Core\Providers;

use Hawese\Core\Mailer;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Support\DeferrableProvider;

class MailerServiceProvider extends ServiceProvider implements DeferrableProvider
{
    public function register()
    {
        $this->mergeConfigFrom(__DIR__ . '/../../config/mail.php', 'mail');

        $this->app->bind(Mailer::class, function ($app) {
            $config = $app['config']['mail'];

            $mailer = new Mailer(true); // True enables exceptions
            $mailer->setFrom($config['from_address'], $config['from_name']);
            $mailer->addReplyTo(
                $config['reply_to_address'],
                $config['reply_to_name']
            );

            switch ($config['driver']) {
                case 'smtp':
                    $mailer->isSMTP();
                    $mailer->Host = $config['host'];
                    $mailer->Port = $config['port'];

                    if ($config['username']) {
                        $mailer->SMTPAuth = true;
                        $mailer->Username = $config['username'];
                        $mailer->Password = $config['password'];
                    }

                    if ($config['encryption']) {
                        $mailer->SMTPSecure = $config['encryption'];
                    }
                    break;
                case 'sendmail':
                    $mailer->isSendmail();
                    break;
                default:
                    $mailer->isMail();
            }

            return $mailer;
        });
    }

    public function provides()
    {
        return [Mailer::class];
    }
}
